var receiverRoot = 'http://www.childdisabilityconnection.org/admin/';
var uploadDestination      = receiverRoot+'uploadFileAIR.php?airAuth=1';
var fileArray   = [];
var fileIDArray = [];
var fn=0; // This is a file array counter
var d=0; // This is a file upload counter
var catJSON;
var subCatJSON;
var conn;

var appInitObj = {
	appInit : function() {
		appLocalDataObj.dataConn();
		appGetDataObj.getCategories('Resource File');
		appDeleteDataObj.clearFilesTable();
	}
}

var appSupportObj = {
	renderMessage : function(type,message) {
		if ($('statusContainer').style.display == 'none') {
			$('statusContainer').style.display = '';
		}
		var typeClass = '';
		switch(type) {
			case 'success':
			typeClass = 'iconUploadComplete';  
			break;    
			case 'error':
			typeClass = 'iconError';  
			break;
			case 'progress':
			typeClass = 'iconInProgress';
			break;
		}
		$('statusIconContainer').className = typeClass;
		$('statusContentContainer').innerHTML = message;
	}
}

var fileSupportObj = {
	pickFiles: function() {
		var rootDir = air.File.documentsDirectory; 
		rootDir.browseForOpenMultiple("Select Files");
		rootDir.addEventListener(air.FileListEvent.SELECT_MULTIPLE, this.fileSelected); 
	},
	openDetailsForm : function(fileID) {
		var idArray  = fileID.split('_');
		var fileID   = idArray[1];
		
		var fileName = $('fileName_'+fileID).innerHTML;
		
		$('fileDetailsContainer').style.display = '';
		$('fileNameEdit').innerHTML = fileName;
		$('fileID').value = fileID;
		$('fileName').value = fileName;
	},
	closeDetailsForm : function() {
		$('fileDetailsContainer').style.display = 'none';
	},
	clearDetailsForm : function() {
		$('fileCat').options.selectedIndex = 0;
		$('fileSubCat').options.length = 0;
		$('subCatContainer').style.display = 'none';
		$('fileTitle').value = '';
		$('fileDesc').value  = '';
	},
	fileSizeCalc : function(fileSize) {
		var convertedSize;
		if (fileSize>1000000) {
			convertedSize = Math.round((fileSize/1000000)*10)/10+'MB';
		} else if (fileSize>1000) {
			convertedSize = Math.round((fileSize/1000)*10)/10+'KB'; 
		} else {
			convertedSize = Math.round(fileSize*10)/10+' bytes';
		}
		return convertedSize;
	},
	fileSelected : function(event) { 
		var fileList = '';
		for (var f = 0; f < event.files.length; f++) {
			var fileName = event.files[f].name;
			var fileSize = fileSupportObj.fileSizeCalc(event.files[f].size);
			var fileContainerId        = 'fileContainerID_'+fn;
			var fileProgressId         = 'fileProgressID_'+fn;
			var fileProgressPercentId  = 'fileProgressPercentID_'+fn;
			var buttonRemoveId         = 'buttonRemove_'+fn;
			var buttonDetailsId        = 'buttonDetails_'+fn;
			var fileNameContainerId    = 'fileName_'+fn;
			fileArray[fn]   = event.files[f];
			fileIDArray[fn] = fn;
			fn++;
			air.trace('Adding file container '+fileContainerId);		
			/*
			 * Append new file div
			 */
			var fileContainer = document.createElement('div');
			fileContainer.setAttribute('id',fileContainerId);
			fileContainer.setAttribute('class','boxFile');
						
			var fileRemoveContainer = document.createElement('div');
			fileRemoveContainer.setAttribute('id',buttonRemoveId);
			fileRemoveContainer.setAttribute('class','buttonDeleteSmall');
			fileRemoveContainer.setAttribute('style','float: left; margin-right: 5px;');
			fileRemoveContainer.onclick = function () { 
				fileManagementObj.removeFile(this.id) 
			};
			
			var fileDetailsContainer = document.createElement('div');
			fileDetailsContainer.setAttribute('id',buttonDetailsId);
			fileDetailsContainer.setAttribute('class','buttonDetailsSmall');
			fileDetailsContainer.setAttribute('style','float: left;');
			fileDetailsContainer.onclick = function () { 
				fileSupportObj.openDetailsForm(this.id) 
			};
			
			var fileNameContainer = document.createElement('div');
			fileNameContainer.setAttribute('id',fileNameContainerId);
			fileNameContainer.setAttribute('style','float: left; margin-left: 10px;');
			fileNameContainer.innerHTML = fileName;
			
			var fileSizeContainer = document.createElement('div');
			fileSizeContainer.setAttribute('style','float: left; margin-left: 10px;');
			fileSizeContainer.innerHTML = fileSize;
			
			var clearLeftContainer = document.createElement('div');
			clearLeftContainer.setAttribute('style','clear: left; height: 20px;');
			
			var fileProgressContainer = document.createElement("div");
			fileProgressContainer.setAttribute('id',fileProgressId);
			fileProgressContainer.setAttribute('class','progressMeter');
			
			fileContainer.appendChild(fileRemoveContainer);
			fileContainer.appendChild(fileDetailsContainer);
			fileContainer.appendChild(fileNameContainer);
			fileContainer.appendChild(fileSizeContainer);
			fileContainer.appendChild(clearLeftContainer);
			fileContainer.appendChild(fileProgressContainer);
			
			$('fileList').appendChild(fileContainer);
			/*
			 * Add new tooltips for file box
			 */
			new Tip(buttonDetailsId,'Edit file details');
			new Tip(buttonRemoveId,'Remove this file');			
		}	
		$('buttonUpload').style.display = '';
	}
}

var fileManagementObj = {
	removeFile: function(containerID) {
		/*
		 * Remove file from fileArray so it doesn't get uploaded
		 */
		var idArray = containerID.split('_');
		var fileID  = idArray[1];
		containerID = 'fileContainerID_'+fileID;
		if ($(containerID)) {	
			fileArray.splice(fileID,1);
			fileIDArray.splice(fileID,1);			
			Effect.Fade(containerID, {delay: .1, duration: 1});
		}	
	}
}

var fileUploadObj = {
	uploadFiles: function(d) {
		/*
		 * Close details form if open
		 */
		fileSupportObj.closeDetailsForm();
		
		if (fileArray[d]) {
			var file   = fileArray[d];
			var fileID = fileIDArray[d];
			progressID = $('fileProgressID_'+fileIDArray[d]);
			percentContainerID = $('fileProgressPercentID_'+fileIDArray[d]);
			appSupportObj.renderMessage('progress','Uploading: '+file.name);
			this.uploadFile(file);
		} else if (fileArray.length == 0) {
			/*
			 * No files were seleted to upload
			 */
			appSupportObj.renderMessage('error','No files were selected to upload.');
		} else {
			/*
			 * Upload Complete
			 */
			
			/*
			 * Remove all file containers
			 */
			for (a=0;a<=(d-1);a++) {
				fileManagementObj.removeFile('fileID_'+a);	
			}
			fileArray.length = 0;
			fileIDArray.length = 0;
			d=0;
			fn=0;
			
			/*
			 * Update status to complete
			 */
			$('statusIconContainer').innerHTML = '';
			appSupportObj.renderMessage('success','Upload Complete!');
			/*
			 * Clear Files table of all records
			 */
			appDeleteDataObj.clearFilesTable();
		}
	},	
	uploadFile: function(file) {
		var variables  = new air.URLVariables('upload=1'); 
		var urlRequest = new air.URLRequest(uploadDestination);
		urlRequest.method = air.URLRequestMethod.POST;
		urlRequest.data   = variables;
		
		file.addEventListener(air.ProgressEvent.PROGRESS, this.fileUploading);			
		file.addEventListener(air.DataEvent.UPLOAD_COMPLETE_DATA, this.fileUploadingComplete);
		file.addEventListener(air.SecurityErrorEvent.SECURITY_ERROR, this.fileUploading);
		file.addEventListener(air.HTTPStatusEvent.HTTP_STATUS, this.fileUploading);
		file.addEventListener(air.IOErrorEvent.IO_ERROR, this.fileUploading);
		file.upload(urlRequest, 'fileUpload');			
	},
	fileUploadingComplete: function(event) {
		/*
		 * Retrieve file information from the database
		 * and send to the server
		 */
		var returnedData = event.data;
		var jsonObject = returnedData.evalJSON();
		var status     = jsonObject.status;
		var message    = jsonObject.msg;
		var fileName   = jsonObject.filename;
		
		/*
		 * Push file details to server
		 */
		appGetDataObj.getFileDetails(fileName);
		d++;
		fileUploadObj.uploadFiles(d);
	},
	fileUploading: function(event) {
		/*
		 * This will handle our upload progress metering and stuff
		 */
		var bytesLoaded = event.bytesLoaded;
		var bytesTotal  = event.bytesTotal;
		var bytesPercentage = Math.ceil((bytesLoaded/bytesTotal)*100);
		this.progressID.innerHTML =  '<div style="width: '+bytesPercentage+'%;" class="progressMeterBar"></div>';
		if (bytesPercentage<100) {
			$('statusIconContainer').innerHTML = bytesPercentage+'%';
		}	
	}
}	